import ENV_CONFIG from "@/env.js"
export default {
	namespaced: true,
	state: {
		PERMISSION_MAP: {
			'userLocation': {
				title: '地理位置',
				androidPermissionID: ['android.permission.ACCESS_FINE_LOCATION'],
				desc: `“${ENV_CONFIG.APP_TITLE_ZH}”需要获取您的地理位置，用于计算统计距离等功能。`
			},
			'writePhotosAlbum': {
				title: '存储空间/相册权限', // 获取手机文件
				androidPermissionID: ['android.permission.WRITE_EXTERNAL_STORAGE'],
				desc: `“${ENV_CONFIG.APP_TITLE_ZH}”需要读写设备上的照片及文件，用于读写/写入图片、文件等功能`
			},
			'camera': {
				title: '相机权限',
				androidPermissionID: ['android.permission.CAMERA'],
				desc: `“${ENV_CONFIG.APP_TITLE_ZH}”需要访问您的相机，用于拍摄图片、视频、个性化头像等功能。`
			},
			'callPhone': {
				title: '拨打电话',
				androidPermissionID: ['android.permission.CALL_PHONE'],
				desc: `“${ENV_CONFIG.APP_TITLE_ZH}”需要拨打电话权限，方便你快速拨打电话。`
			}
		},
		isIos: (plus.os.name == "iOS"),
		premission: {},
		viewObj: null
	},
	mutations: {
		/**
		 * 统一修改state某个key数据
		 * @param {Object} state
		 * @param {Object} payload -name>要修改的属性 key>要修改的字段 value>要修改的数据
		 */
		$setStoreKey(state, payload) {
			state[payload.name][payload.key] = payload.value
		}
	},
	actions: {
		async requestPermissions({
			state,
			dispatch,
			commit
		}, permissionID) {
			if (!state.premission[permissionID] && !state.isIos) {
				var viewObj = await dispatch('nativeObjView', permissionID);
				commit('$setStore', {
					path: 'viewObj',
					value: viewObj
				})
				viewObj.show();
			}
			return new Promise(async (resolve, reject) => {
				const res = await dispatch('checkAuth', permissionID)
				resolve(res)
			})
		},
		//权限检测
		async checkAuth({
			state,
			dispatch,
			commit
		}, permissionID) {
			let result = false
			switch (permissionID) {
				case 'userLocation': //定位权限
					result = state.isIos ? dispatch('iosLocationAuth') : await dispatch('androidAuth', permissionID)
					break;
				case 'writePhotosAlbum': //相册权限
					result = state.isIos ? dispatch('iosPhotoAuth') : await dispatch('androidAuth', permissionID)
					break;
				case 'camera': //摄像头权限
					result = state.isIos ? dispatch('iosCameraAuth') : await dispatch('androidAuth', permissionID)
					break;
				case 'callPhone': //拨打电话
					result = state.isIos ? dispatch('iosCameraAuth') : await dispatch('androidAuth', permissionID)
					break;
				default:
					result = false
					break;
			}
			return Promise.resolve(result)
		},
		// Android权限查询
		androidAuth({
			state,
			dispatch,
			commit
		}, permissionVal) {
			const that = this;
			let permissionID = state.PERMISSION_MAP[permissionVal].androidPermissionID;
			return new Promise((resolve, reject) => {
				plus.android.requestPermissions(
					[...permissionID], // 理论上支持多个权限同时查询，但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
					function(resultObj) {
						let result = 0;
						for (var i = 0; i < resultObj.granted.length; i++) {
							var grantedPermission = resultObj.granted[i];
							console.log('已获取的权限：' + grantedPermission);
							result = 1
						}
						for (var i = 0; i < resultObj.deniedPresent.length; i++) {
							var deniedPresentPermission = resultObj.deniedPresent[i];
							console.log('拒绝本次申请的权限：' + deniedPresentPermission);
							result = 0
						}
						for (var i = 0; i < resultObj.deniedAlways.length; i++) {
							var deniedAlwaysPermission = resultObj.deniedAlways[i];
							console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
							result = -1
						}

						if (result === 1) {
							//'已获得授权'
							commit('$setStore', {
								path: `premission.${permissionVal}`,
								value: true
							})
						} else if (result === 0) {
							//'未获得授权'
							commit('$setStore', {
								path: `premission.${permissionVal}`,
								value: false
							})
							/* commit('$setStoreKey', {
								name:'premission',
								key:permissionVal,
								value:false
							}) */
						} else {
							commit('$setStore', {
								path: `premission.${permissionVal}`,
								value: false
							})
							dispatch('gotoAppSetting')
						}
						console.log(state.premission, result);
						resolve(result);
						if (state.viewObj) state.viewObj.close()
					},
					function(error) {
						console.log('申请权限错误：' + error.code + " = " + error.message);
						resolve({
							code: error.code,
							message: error.message
						});
					}
				);
			});
		},
		// 跳转到**应用**的权限页面
		gotoAppSetting({
			state,
			dispatch,
			commit
		}) {
			uni.showModal({
				title: '设置权限',
				content: `操作权限已被拒绝，请手动前往设置`,
				confirmText: '去设置',
				success: res => {
					if (res.confirm) {
						if (state.isIos) {
							let UIApplication = plus.ios.import("UIApplication");
							let application2 = UIApplication.sharedApplication();
							let NSURL2 = plus.ios.import("NSURL");
							let setting2 = NSURL2.URLWithString("app-settings:");
							application2.openURL(setting2);
							plus.ios.deleteObject(setting2);
							plus.ios.deleteObject(NSURL2);
							plus.ios.deleteObject(application2);
						} else {
							let Intent = plus.android.importClass("android.content.Intent");
							let Settings = plus.android.importClass("android.provider.Settings");
							let Uri = plus.android.importClass("android.net.Uri");
							let mainActivity = plus.android.runtimeMainActivity();
							let intent = new Intent();
							intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
							let uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
							intent.setData(uri);
							mainActivity.startActivity(intent);
						}
					}
				},
				fail: err => {
					console.log(`%cuni.showModal失败：`, 'color:green;background:yellow');
				}
			})
		},
		// 定位是否开启
		iosLocationAuth() {
			let result = 0;
			let cllocationManger = plus.ios.import("CLLocationManager");
			let enable = cllocationManger.locationServicesEnabled();
			let status = cllocationManger.authorizationStatus();
			if (!enable) {
				result = 2;
			} else if (status === 0) {
				result = null;
			} else if (status === 3 || status === 4) {
				result = 1;
			} else {
				result = 0;
			}
			plus.ios.deleteObject(cllocationManger);
			return result;
		},
		nativeObjView({
			state
		}, permissionID) {
			const systemInfo = uni.getSystemInfoSync();
			const statusBarHeight = systemInfo.statusBarHeight;
			const navigationBarHeight = systemInfo.platform === 'android' ? 48 :
				44; // Set the navigation bar height based on the platform
			const totalHeight = statusBarHeight + navigationBarHeight;
			let view = new plus.nativeObj.View('per-modal', {
				top: '0px',
				left: '0px',
				width: '100%',
				backgroundColor: '#444',
				//opacity: .5;
			})
			view.drawRect({
				color: '#fff',
				radius: '5px'
			}, {
				top: totalHeight + 'px',
				left: '5%',
				width: '90%',
				height: "100px",
			})
			view.drawText(state.PERMISSION_MAP[permissionID].title, {
				top: totalHeight + 5 + 'px',
				left: "8%",
				height: "30px"
			}, {
				align: "left",
				color: "#000",
			}, {
				onClick: function(e) {
					console.log(e);
				}
			})
			view.drawText(state.PERMISSION_MAP[permissionID].desc, {
				top: totalHeight + 35 + 'px',
				height: "60px",
				left: "8%",
				width: "84%"
			}, {
				whiteSpace: 'normal',
				size: "14px",
				align: "left",
				color: "#656563"
			})

			function show() {
				view = plus.nativeObj.View.getViewById('per-modal');
				view.show()
				view = null //展示的时候也得清空，不然影响下次的关闭，不知道为啥
			}

			function close() {
				view = plus.nativeObj.View.getViewById('per-modal');
				view.close();
				view = null
			}
			return {
				show,
				close
			}
		},
	}
}